package buildTree;

import util.TreeNode;

import java.util.HashMap;
import java.util.Map;

/**
 * @program: javase
 * @description: 中序，后序构建二叉树
 * @author: luolidong
 * @create: 2021-07-02 19:45
 * @version: 1.0
 */
public class BuildTreeByInPostOrder {
    public TreeNode buildTree(int[] inorder, int[] postorder) {
        Map<Integer,Integer> map=new HashMap<>();
        for (int i = 0; i <inorder.length ; i++) {
            map.put(inorder[i],i);
        }

        return build(postorder,0,inorder.length-1,map,0,postorder.length-1);
    }

    private TreeNode build(int[] postorder,int inLeft, int inRight,
                           Map<Integer, Integer> map, int postLeft, int postRight) {
        if(inLeft>inRight||postLeft>postRight) return null;
        int rootVal=postorder[postRight];
        TreeNode root = new TreeNode(rootVal);
        int pIndex=map.get(rootVal);

        root.right=build(postorder, pIndex+1, inRight, map, pIndex+postRight-inRight, postRight-1);
        root.left=build(postorder, inLeft, pIndex-1, map, postLeft, pIndex+postRight-inRight-1);

        return root;
    }
    private TreeNode build2(int[] pre, int[] post,int preLeft, int preRight,
                            int postLeft, int postRight) {
        if(postLeft>postRight||preLeft>preRight) return null;
        TreeNode root = new TreeNode(pre[preLeft]);

        root.left=build2(pre,post,preLeft+1,preLeft+1, postLeft, postRight);
        root.right=build2(pre,post,preLeft+postLeft-postRight,preRight, postLeft+1, postRight-1);

        return root;
    }
}
